<?php

		include_once('opendb.php');
		include_once('config.php');

		if($db){
			echo "Connected <br />";
		}

		if(!$db->query("DROP TABLE IF EXISTS animals;") ||
			!$db->query("CREATE  TABLE $dbname.`animals` (

						  `petID` INT NOT NULL ,

						  `name` VARCHAR(45) NOT NULL ,

						  `breeds` VARCHAR(45) NOT NULL ,

						  `sex` VARCHAR(45) NOT NULL ,

						  `size` VARCHAR(45) NOT NULL ,

						  `age` VARCHAR(45) NOT NULL ,

						  `status` VARCHAR(45) NOT NULL ,

						  `lastUpdate` VARCHAR(45) NOT NULL ,

						  `options` VARCHAR(45) NOT NULL ,

						  `description` VARCHAR(3000) NOT NULL ,

						  `pic1` VARCHAR(100) NULL ,

						  `pic2` VARCHAR(100) NULL ,

						  `pic3` VARCHAR(100) NULL ,

						  `pic1Thumb` VARCHAR(100) NULL ,

						  `pic2Thumb` VARCHAR(100) NULL ,

						  `pic3Thumb` VARCHAR(100) NULL ,

							PRIMARY KEY (`petID`)

							  );

					")  ||
			!$db->query("ALTER TABLE $dbname.`animals` CHARACTER SET = utf8 ;"))
			echo "Table creation failed: (" . $db->errno . ") " . $db->error;

		include_once('class.petfinder.php');

		$pet = new Petfinder;
		$pet->setKey($key);
		$pet->setPass($pass);

		$pet->getToken();

		$pet->set( array('cache_enable' => FALSE) );

		$config = array('id'=>$shelterNum);

		$pet->initialize($config);
		$data = $pet->shelterGetPets();

		$query = "INSERT INTO animals (petID, name, breeds, sex, size, age, status, lastUpdate, options, description, pic1, pic2, pic3, pic1Thumb, pic2Thumb, pic3Thumb) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

		for ($i=0; $i < count($data); $i++) {

			$petID = $data[$i]['id'];
			$name = $data[$i]['name'];
			$breeds = $data[$i]['breeds'];
			$sex = $data[$i]['sex'];
			$size = $data[$i]['size'];
			$age = $data[$i]['age'];
			$status = $data[$i]['status'];
			$lastUpdate = $data[$i]['lastUpdate'];
			$options = $data[$i]['options'];
			$desc = $data[$i]['description'];
			$pic1 = $data[$i]['photo']['1']['pn'];
			$pic1Thumb = $data[$i]['photo']['1']['pnt'];
			$pic2 = $data[$i]['photo']['2']['pn'];
			$pic2Thumb = $data[$i]['photo']['2']['pnt'];

			$pic3 = $data[$i]['photo']['3']['pn'];
			$pic3Thumb = $data[$i]['photo']['3']['pnt'];

			$stmt = $db->stmt_init();

			if($stmt->prepare($query)) {


				$stmt->bind_param("isssssssssssssss", $petID, $name, $breeds, $sex, $size, $age, $status, $lastUpdate, $options, $desc, $pic1, $pic2, $pic3, $pic1Thumb, $pic2Thumb, $pic3Thumb);

				if(!$stmt->execute()) {
					echo "failed: (" . $db->errno . ") " . $db->error;
				}

				$stmt->fetch();

				$stmt->close();
			}else {
				echo "failed at " . $name . ": (" . $db->errno . ") " . $db->error;
			}

		}

		echo "Database imported <br />";

		include_once('closedb.php');
    
?>